import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:nft_shop/box/page/details/box_details_page.dart';
import 'package:nft_shop/market/conteroller/market_conteroller.dart';
import 'package:nft_shop/market/model/models.dart';
import 'package:nft_shop/market/page/details/works_3d_details_page.dart';
import 'package:nft_shop/market/page/details/works_details_page.dart';
import 'package:nft_shop/net/service_repository.dart';
import 'package:nft_shop/res/constant.dart';
import 'package:nft_shop/res/global.dart';
import 'package:nft_shop/util/route_observer.dart';
import 'package:nft_shop/widgets/load_image.dart';
import 'package:nft_shop/widgets/status_view.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class MarketListPage extends StatefulWidget {
  int index;

  MarketListPage({Key? key, required this.index}) : super(key: key);

  @override
  _MarketListPageState createState() => _MarketListPageState();
}

class _MarketListPageState extends State<MarketListPage>
    with AutomaticKeepAliveClientMixin, RouteAware {
  MarketConteroller? _conteroller;

  /// 分页第一页页码
  static const int pageNumFirst = 1;

  /// 当前第几页
  int currentPageNum = pageNumFirst;

  /// 分页条目数量
  int pageSize = 20;

  /// 页面数据
  List list = [];

  ///状态
  int _status = LoadStatusType.loading;

  ///刷新组件
  RefreshController refreshController =
      RefreshController(initialRefresh: false);

  int get status => _status;

  set status(int value) {
    _status = value;
    setState(() {});
  }

  @override
  bool get wantKeepAlive => true;

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    RouteUtils.routeObserver
        .subscribe(this, ModalRoute.of(context) as PageRoute);
  }

  @override
  void dispose() {
    RouteUtils.routeObserver.unsubscribe(this);
    super.dispose();
  }

//回到当前页面
  @override
  void didPopNext() {
    refresh();
    print("市场返回刷新了---");
  }

  @override
  void initState() {
    super.initState();
    _conteroller = MarketConteroller.to;
    refresh();
  }

  //获取数据
  Future<List> loadData({int? pageNum}) async {
    //首发
    if (widget.index == 0) {
      return await ServiceRepository.goodsSpecialList(
          page: pageNum!,
          pageSize: pageSize,
          isHot: 0,
          type: _conteroller!.selectCategoryNum,
          orderType: _conteroller!.orderType);
    } else {
      //转售
      return await ServiceRepository.goodsList(
          page: pageNum!,
          pageSize: pageSize,
          type: _conteroller!.selectSellCategoryNum,
          orderType: _conteroller!.turnOrderType);
    }
  }

  /// 下拉刷新
  ///
  /// [init] 是否是第一次加载
  /// true:  Error时,需要跳转页面
  /// false: Error时,不需要跳转页面,直接给出提示
  Future<List?> refresh({bool init = false}) async {
    try {
      currentPageNum = pageNumFirst;
      var data = await loadData(pageNum: pageNumFirst);
      EasyLoading.dismiss();
      if (data.isEmpty) {
        refreshController.refreshCompleted(resetFooterState: true);
        list.clear();
        status = LoadStatusType.empty;
      } else {
        list.clear();
        list.addAll(data);
        refreshController.refreshCompleted();
        // 小于分页的数量,禁止上拉加载更多
        if (data.length < pageSize) {
          // refreshController.loadNoData();
        } else {
          //防止上次上拉加载更多失败,需要重置状态
          refreshController.loadComplete();
        }
        status = LoadStatusType.success;
      }
      return data;
    } catch (e, s) {
      EasyLoading.dismiss();

      /// 页面已经加载了数据,如果刷新报错,不应该直接跳转错误页面
      /// 而是显示之前的页面数据.给出错误提示
      if (init) list.clear();
      refreshController.refreshFailed();
      status = LoadStatusType.empty;
      // setError(e, s);
      return null;
    }
  }

  /// 上拉加载更多
  Future<List?> loadMore() async {
    try {
      var data = await loadData(pageNum: ++currentPageNum);
      if (data.isEmpty) {
        currentPageNum--;
        // refreshController.loadNoData();
        refreshController.loadComplete();
      } else {
        list.addAll(data);
        if (data.length < pageSize) {
          // refreshController.loadNoData();
          refreshController.loadComplete();
        } else {
          refreshController.loadComplete();
        }
        setState(() {});
      }
      return data;
    } catch (e, s) {
      currentPageNum--;
      refreshController.loadFailed();
      return null;
    }
  }

  @override
  Widget build(BuildContext context) {
    _conteroller!.onPressed = () async {
      await EasyLoading.show(
        status: 'loading...',
      );
      refresh(init: true);
    };
    return Column(
      children: [
        topWidget(),
        Expanded(child: _gridViewWidget()),
      ],
    );
  }

  Widget topWidget() {
    return GetBuilder<MarketConteroller>(
        id: widget.index == 0
            ? MarketConteroller.MarketStartingID
            : MarketConteroller.MarketResaleID,
        builder: (logic) {
          return Container(
            padding: EdgeInsets.symmetric(horizontal: 15, vertical: 5),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                InkWell(
                  onTap: () {
                    logic.changeSortingTime(widget.index);
                    refresh();
                  },
                  child: Text.rich(
                    TextSpan(children: [
                      TextSpan(
                        text: "发布时间",
                        style: TextStyle(
                            fontSize: 14,
                            fontFamily: Global.mySemiboldFont,
                            color: Global.kTheme.textPrimary3),
                      ),
                      WidgetSpan(
                          child: SizedBox(
                        width: 4,
                      )),
                      WidgetSpan(
                        child: _sortingWidget(widget.index == 0
                            ? logic.startingTimeType
                            : logic.resaleTimeType),
                        alignment: PlaceholderAlignment.middle,
                      ),
                    ]),
                    textAlign: TextAlign.center,
                  ),
                ),
                InkWell(
                  onTap: () {
                    logic.changeSortingPrice(widget.index);
                    refresh();
                  },
                  child: Text.rich(
                    TextSpan(
                      children: [
                        TextSpan(
                          text: "价格",
                          style: TextStyle(
                              fontSize: 14,
                              fontFamily: Global.mySemiboldFont,
                              color: Global.kTheme.textPrimary3),
                        ),
                        WidgetSpan(
                            child: SizedBox(
                          width: 4,
                        )),
                        WidgetSpan(
                          child: _sortingWidget(widget.index == 0
                              ? logic.startingPriceType
                              : logic.resalePriceType),
                          alignment: PlaceholderAlignment.middle,
                        ),
                      ],
                    ),
                    textAlign: TextAlign.center,
                  ),
                ),
              ],
            ),
          );
        });
  }

  ///藏品
  Widget _gridViewWidget() {
    return SmartRefresher(
      controller: refreshController,
      header: WaterDropHeader(),
      footer: ClassicFooter(),
      onRefresh: refresh,
      onLoading: loadMore,
      enablePullUp: true,
      child: _bulideGridView(),
    );
  }

  _bulideGridView() {
    if (status != LoadStatusType.success) {
      return StatusViews(status);
    }
    return GridView.builder(
      padding: EdgeInsets.symmetric(horizontal: 15, vertical: 15),
      physics: BouncingScrollPhysics(),
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 2,
        crossAxisSpacing: 15,
        mainAxisSpacing: 15,
        childAspectRatio: 167 / 230,
      ),
      //maxCrossAxisExtent
      itemBuilder: (context, index) {
        //首发
        if (widget.index == 0) {
          GoodsSpecialList model = list[index];
          return _itemWidget1(model);
        } else {
          GoodsList model = list[index];
          return _itemWidget2(model);
        }
      },
      itemCount: list.length,
    );
  }

  ///item1
  Widget _itemWidget1(GoodsSpecialList model) {
    double itemWidth = (Get.width - 45) / 2;
    double itemHeight = (itemWidth * 173) / 167;
    return InkWell(
      //1单个藏品详情 2整体铸造详情  3整体详情
      //1藏品 2盲盒
      onTap: () {
        print("选中---${model.type}");
        if (model.type == 1) {
          //3D
          if (model.specialTypeId == 2) {
            Get.to(Works3DDetailsPage(
              id: model.id!,
              type: 3,
            ));
          } else {
            Get.to(WorksDetailsPage(
              id: model.id!,
              type: 3,
            ));
          }
        } else {
          Get.to(BoxDetailsPage(id: model.id!, type: 3));
        }
      },
      child: Container(
        decoration: BoxDecoration(
            color: Global.kTheme.colorBackground1,
            borderRadius: BorderRadius.circular(10.0),
            boxShadow: [
              BoxShadow(
                  color: Color(0x80E6E6E6),
                  offset: Offset(2.0, 2.0), //阴影xy轴偏移量
                  blurRadius: 8.0, //阴影模糊程度
                  spreadRadius: 3.0 //阴影扩散程度
                  )
            ]),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Stack(
              children: [
                ClipRRect(
                  borderRadius: BorderRadius.circular(10),
                  child: LoadImage(
                    model.thumb ?? "",
                    width: double.infinity,
                    fit: BoxFit.fitHeight,
                    height: itemHeight,
                  ),
                ),
                Positioned(
                  left: 9,
                  top: 8,
                  child: _objectState(widget.index == 0
                      ? model.num == 0
                          ? "已售罄"
                          : (model.is_will_status! == 1 ? "首发预售中" : "首发售卖中")
                      : model.type == 1
                          ? model.num == 0
                              ? "已售罄"
                              : "转售中"
                          : model.num == 0
                              ? "已售罄"
                              : (model.type == 2 ? "盲盒未拆" : "盲盒已拆")),
                ),
                Visibility(
                  visible: ObjectUtil.isEmptyString(model.specialTypeName)
                      ? false
                      : true,
                  child: Positioned(
                    bottom: 5,
                    left: 5,
                    child: _objectType(model.specialTypeName ?? ""),
                  ),
                ),
              ],
            ),
            Container(
              padding: EdgeInsets.symmetric(horizontal: 10, vertical: 8),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          model.title ?? "",
                          maxLines: 1,
                          style: TextStyle(
                              fontFamily: Global.mySemiboldFont,
                              fontSize: 14,
                              color: Global.kTheme.textPrimary4),
                        ),
                        SizedBox(
                          height: 2,
                        ),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.start,
                          children: [
                            ClipRRect(
                              borderRadius: BorderRadius.circular(9),
                              child: LoadImage(
                                model.portrait!.length == 0
                                    ? "header_img"
                                    : model.portrait!,
                                width: 18,
                                height: 18,
                                holderImg: "header_img",
                              ),
                            ),
                            SizedBox(
                              width: 4,
                            ),
                            Expanded(
                              child: Text(
                                model.nickname ?? "",
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                                style: TextStyle(
                                    fontSize: 12,
                                    color: Global.kTheme.textPrimary0,
                                    fontFamily: Global.mySemiboldFont),
                              ),
                            ),
                          ],
                        )
                      ],
                    ),
                  ),
                  Text(
                    "¥${model.basePrice}",
                    style: TextStyle(
                        fontFamily: Global.myDINFont,
                        color: Global.kTheme.textPrimary0,
                        fontSize: 16),
                  ),
                ],
              ),
            )
          ],
        ),
      ),
    );
  }

  ///item2
  Widget _itemWidget2(GoodsList model) {
    double itemWidth = (Get.width - 45) / 2;
    double itemHeight = (itemWidth * 173) / 167;
    return InkWell(
      //1单个藏品详情 2整体铸造详情  3整体详情
      onTap: () {
        if (model.type == 1) {
          //3D
          if (model.specialTypeId == 2) {
            Get.to(Works3DDetailsPage(
              id: model.id!,
              type: 1,
            ));
          } else {
            Get.to(WorksDetailsPage(
              id: model.id!,
              type: 1,
            ));
          }
        } else {
          Get.to(BoxDetailsPage(
            id: model.id!,
            type: 1,
          ));
        }
      },
      child: Container(
        decoration: BoxDecoration(
            color: Global.kTheme.colorBackground1,
            borderRadius: BorderRadius.circular(10.0),
            boxShadow: [
              BoxShadow(
                  color: Color(0x80E6E6E6),
                  offset: Offset(2.0, 2.0), //阴影xy轴偏移量
                  blurRadius: 8.0, //阴影模糊程度
                  spreadRadius: 3.0 //阴影扩散程度
                  )
            ]),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Stack(
              children: [
                ClipRRect(
                  borderRadius: BorderRadius.circular(10),
                  child: LoadImage(
                    model.thumb ?? "",
                    width: double.infinity,
                    fit: BoxFit.fitHeight,
                    height: itemHeight,
                  ),
                ),
                Positioned(
                  left: 9,
                  top: 8,
                  child: _objectState(model.num == 0 ? "已售罄" : "售卖中"),
                ),
                Visibility(
                  visible: ObjectUtil.isEmptyString(model.specialTypeName)
                      ? false
                      : true,
                  child: Positioned(
                    bottom: 5,
                    left: 5,
                    child: _objectType(model.specialTypeName ?? ""),
                  ),
                ),
              ],
            ),
            Container(
              padding: EdgeInsets.symmetric(horizontal: 10, vertical: 8),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          model.title ?? "",
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(
                              fontFamily: Global.mySemiboldFont,
                              fontSize: 14,
                              color: Global.kTheme.textPrimary4),
                        ),
                        SizedBox(
                          height: 2,
                        ),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.start,
                          children: [
                            ClipRRect(
                              borderRadius: BorderRadius.circular(9),
                              child: LoadImage(
                                model.portrait ?? "",
                                width: 18,
                                height: 18,
                                holderImg: "header_img",
                              ),
                            ),
                            SizedBox(
                              width: 4,
                            ),
                            Expanded(
                              child: Text(
                                model.nickname ?? "",
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                                style: TextStyle(
                                    fontSize: 12,
                                    color: Global.kTheme.textPrimary0,
                                    fontFamily: Global.mySemiboldFont),
                              ),
                            ),
                          ],
                        )
                      ],
                    ),
                  ),
                  Text(
                    "¥${model.price}",
                    style: TextStyle(
                        fontFamily: Global.myDINFont,
                        color: Global.kTheme.textPrimary0,
                        fontSize: 16),
                  ),
                ],
              ),
            )
          ],
        ),
      ),
    );
  }

  ///藏品状态
  Widget _objectState(String state) {
    return Container(
      height: 24,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(12),
        color: Global.kTheme.colorBackground3.withAlpha(100),
      ),
      padding: EdgeInsets.symmetric(horizontal: 10, vertical: 4),
      child: Text(
        state,
        style: TextStyle(
            color: Global.kTheme.textPrimary5,
            fontSize: 12,
            fontFamily: Global.mySemiboldFont),
      ),
    );
  }

  ///藏品类型
  Widget _objectType(String state) {
    return Container(
      height: 17,
      decoration: BoxDecoration(
        color: Global.kTheme.colorBackground3,
      ),
      padding: EdgeInsets.symmetric(horizontal: 5, vertical: 2),
      child: Text(
        state,
        style: TextStyle(
            color: Global.kTheme.textPrimary5,
            fontSize: 10,
            fontFamily: Global.mySemiboldFont),
      ),
    );
  }

  //排序
  Widget _sortingWidget(
    int type,
  ) {
    String iconTop = "grey_top";
    String iconBottom = "grey_bottom";
    if (type == 0) {
      iconTop = "grey_top";
      iconBottom = "grey_bottom";
    } else if (type == 1) {
      iconTop = "black_top";
      iconBottom = "grey_bottom";
    } else if (type == 2) {
      iconTop = "grey_top";
      iconBottom = "black_bottom";
    }
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        LoadAssetImage(
          iconTop,
          width: 10,
          height: 5,
        ),
        SizedBox(
          height: 2,
        ),
        LoadAssetImage(
          iconBottom,
          width: 10,
          height: 5,
        ),
      ],
    );
  }
}
